package com.itheima.app.interceptor;

import cn.hutool.core.util.StrUtil;
import com.itheima.app.manager.UserManager;
import com.itheima.domain.db.User;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//创建拦截器
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private UserManager userManager;
    @Override//预处理
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取token
        String token = request.getHeader("Authorization");
        //如果不存在返回错误页面
        if (StrUtil.isEmpty(token)){
            response.setStatus(401);
            return false;
        }
        //根据token获取user对象
        User user=userManager.findUserByToken(token);
        //如果为空返回错误页面
        if (user==null){
            response.setStatus(401);
            return false;
        }
        //把user对象存入自定义ThreadLocal里
        UserHolder.set(user);
        return true;
    }

    @Override//最终处理
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //把user与ThreadLocal解绑
     UserHolder.remove();
    }
}
